// ------------- demo ---------------------
var updateTotalCount = function(url) {
	var container = document.getElementById("totalNumber");
	container.innerHTML = "";
	
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if( (xmlHttp.readyState == 4) && (xmlHttp.status == 200 )) {
			var countDiv = document.getElementById('totalNumber');
			countDiv.innerHTML = xmlHttp.responseText + "<span style='font-size:12px;'>条微博</span>";
		}
	};
	var start = document.getElementById("startTimeInput").value;
	var end = document.getElementById("endTimeInput").value;
	
	xmlHttp.open('get', url + "&timeFrom="+start+"&timeTo="+end );
	xmlHttp.send(null);
};

var updateDemoBrand = function(id, url) {
	var container = document.getElementById(id);
	container.innerHTML = "";
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if( (xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
			var xml = xmlHttp.responseText;
			flash.writeFlash({isReplace:false, url:"../weibo/flex/CustomColumnChart.swf", 
				id:id + Math.random(),
				containerId:id,
				width:"400", height:"200",
				flashvars:{data:encodeURIComponent(xml)}});
		}
	};
	var start = document.getElementById("startTimeInput").value;
	var end = document.getElementById("endTimeInput").value;
	xmlHttp.open('get', url+ "&timeFrom="+start+"&timeTo="+end );
	xmlHttp.send(null);
};

var updateDemoBrandTrend = function(id, url) {
	var container = document.getElementById(id);
	container.innerHTML = "";
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if( (xmlHttp.readyState == 4) && (xmlHttp.status == 200 ) ){
			var xml = xmlHttp.responseText;		
			flash.writeFlash({isReplace:false, url:"../weibo/flex/CustomLineChart.swf", 
				id:id + Math.random(), 
				containerId:id, 
				width:"400", height:"200",flashvars:{data:encodeURIComponent(xml)}});
		}
	};
	var start = document.getElementById("startTimeInput").value;
	var end = document.getElementById("endTimeInput").value;
	xmlHttp.open('get', url+"&timeFrom="+start+"&timeTo="+end);
	xmlHttp.send(null);
};


// -------------- demo -----------------------


var addDropDownlist = function( id, items, callback ) {
	var selector = document.getElementById(id);
	selector.innerHTML = "";
	if( !items )
		return;
	for(var i=0; i<items.length; i++) {
		var option = document.createElement('Option');
		option.value = items[i].value;
		option.text = items[i].category;
		option.onclick = (function( d ) {
			return function() {
				callback( d );
			};
		})( items[i].value);
		
		selector.appendChild(option);
	}
};

var updateWeiboFansCount = function(url) {
	if( url == null)
		return;
	
	var container = document.getElementById("weiboFansCount");
	container.innerHTML = "";
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange= function() {
		if( (xmlHttp.readyState == 4 )&& ( xmlHttp.status == 200) ) {
			
			var data = JSON.parse( xmlHttp.responseText );
			if( !data )
				return;
			var label = document.getElementById("weiboFansCount");
			label.innerHTML = data;
			return;
		}
	};
	var start = document.getElementById("startTimeInput").value;
	var end = document.getElementById("endTimeInput").value;
	xmlHttp.open('get', url+"&timeFrom="+start+"&timeTo="+end);
//	xmlHttp.open('get', url);
	xmlHttp.send(null);
};

var updateArea = function(url) {
	var container = document.getElementById("areaChart");
	container.innerHTML = "";
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if( (xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
			var xml = xmlHttp.responseText;
			flash.writeFlash({isReplace:false, url:"../weibo/flex/CustomBarChart.swf", id:"area", containerId:"areaChart", width:"250", height:"200",flashvars:{data:encodeURIComponent(xml)}});
			
			/*var data = JSON.parse( xmlHttp.responseText );
			if( !data )
				return;
			var margin = {top:0, right: 40, bottom:10, left: 40},
				width = 200 - margin.left - margin.right,
				height = 200;
			
			var x = d3.scale.ordinal().rangeRoundBands([0, height], .1);
				x.domain( data.map( function(d){return d.location; } ));
					
			var y = d3.scale.linear()
				.domain([0, d3.max(data, function(d){ return d.count; }) ])
				.        ange([0, width]);
			var container = document.getElementById("areaChart");
			container.innerHTML = "";
			
			var vis = d3.select("#areaChart")
				.append("svg")
				.attr("width", 200)
				.attr("height", 200);
			
			var bar = vis.selectAll('g')
				.data( data)
				.enter()
				.append("g");
				
			bar.append('rect')
				.attr('x', margin.left)
				.attr("width", function(d) { return y(d.count); } )
				.attr("height", 15)
				.attr("fill", "#00AAFF")
				.attr("transform", function(d, i){ return "translate(0, "+ 20 * i + ")"; } )
				.on("click", function(d){ console.log(d); showWeiboList(d.ids);  });;
				
			bar.append("text")
				.attr('x', margin.left )
				.attr('y', function(d, i) { return 20 * i + 10; })
				.attr("text-anchor", "end")
				.text( function(d) { return d.location; } );
			bar.append("text")
				.attr('x', function(d){ return margin.left + y(d.count);})
				.attr('y', function(d, i) { return 20 * i + 10;})
				.text( function(d) {return d.count;} );*/
		}
	};
	var start = document.getElementById("startTimeInput").value;
	var end = document.getElementById("endTimeInput").value;
	xmlHttp.open('get', url+ "&timeFrom="+start+"&timeTo="+end );
	xmlHttp.send(null);
};

var updateOpinionLeader = function(url) {
	var container = document.getElementById("opinionLeaderChart");
	container.innerHTML = "";
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if( (xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
			var xml = xmlHttp.responseText;
			flash.writeFlash({isReplace:false, url:"../weibo/flex/CustomBarChart.swf", id:"opinionLeader", containerId:"opinionLeaderChart", width:"250", height:"200",flashvars:{data:encodeURIComponent(xml)}});
			
			/*
			var data = JSON.parse( xmlHttp.responseText );
			if( !data )
				return;
			var margin = {top:0, right: 50, bottom:10, left: 100},
				width = 200 - margin.left - margin.right,
				height = 200;
			
			var x = d3.scale.ordinal().rangeRoundBands([0, height], .1);
				x.domain( data.map( function(d){return d.name; } ));
					
			var y = d3.scale.linear()
				.domain([0, d3.max(data, function(d){ return d.fans; }) ])
				.range([0, width]);
				
			var vis = d3.select("#opinionLeaderChart")
				.append("svg")
				.attr("width", 200)
				.attr("height", 200);
			
			var bar = vis.selectAll('g')
				.data( data)
				.enter()
				.append("g");
				
			bar.append('rect')
				.attr('x', margin.left)
				.attr("width", function(d) { return y(d.fans); } )
				.attr("height", 15)
				.attr("fill", "#00AAFF")
				.attr("transform", function(d, i){ return "translate(0, "+ 20 * i + ")"; } )
				.on("click", function(d){ showWeiboList(d.ids);  });
				
				
			bar.append("text")
				.attr('x', margin.left )
				.attr('y', function(d, i) { return 20 * i + 12; })
				.attr("text-anchor", "end")
				.text( function(d) { return d.name; } );
			
			bar.append("text")
				.attr('x', function(d){ return margin.left + y(d.fans);})
				.attr('y', function(d, i) { return 20 * i + 12;})
				.text( function(d) {return d.fans;} );*/
		}
	};
	var start = document.getElementById("startTimeInput").value;
	var end = document.getElementById("endTimeInput").value;
	xmlHttp.open('get', url+ "&timeFrom="+start+"&timeTo="+end );
//	xmlHttp.open('get', url);
	xmlHttp.send(null);
};

var updateTopicKeywords = function(url) {
	var container = document.getElementById("topicChart");
	container.innerHTML = "";
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if( (xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
			if( !xmlHttp.responseText ) {
				return;
			}
			 var data = JSON.parse( xmlHttp.responseText );
			 if( !data )
				return ;				
			
			var color2 = ['#FFAA00', '#00FFAA', '#AAFF00', '#FF0000', '#AA00FF'];
			//var color = ['rgb(249, 127, 56)', 'rgb(54, 54, 54)'];
			var color = ['rgb(54, 54, 54)', 'rgb(54, 54, 54)'];
			
			var chart = document.getElementById("topicChart");
			chart.innerHTML = "";
			
			var sum = 0;
			for(var j=0; j<data.length; j++)
				sum += data[j].weight;
			
			var limit = data.length  < 15 ? data.length : 15;
			var i=0;
			var middle = data[ Math.floor( limit/ 2) ].weight;
			data.sort( function(a, b) {
				return a.weight < b.weight;
			});
			
			var slicedata = data.slice(0, limit);
			//slicedata.sort(function(){return Math.random()>0.5?-1:1;});
			
			 var max = 1;
			 var min= 1000000;
			for(var j=0; j< slicedata.length; j++) {
				if( max < slicedata[j].weight )
					max = slicedata[j].weight;
				if( min > slicedata[j].weight ) 
					min = slicedata[j].weight;
			}
			
			var scale = 6;
			if( max > 200 ) scale = scale + 1;
			if( max > 500 ) scale = scale + 1;
			if( max > 1000 ) scale = scale + 1;
			if( max > 2000 ) scale = scale + 1;
			if( max > 5000 ) scale = scale + 2;
			if( max > 10000 ) scale = scale + 2;
			if( max > 50000 ) scale = scale + 2;
			
			for( i=0; i<limit; i++) {
				var item = document.createElement('p');
				var cleanKeyword = slicedata[i].keyword.replace(/#/g, '');
				item.innerHTML = cleanKeyword;
				
				item.title = slicedata[i].weight + "  " + (slicedata[i].weight/sum).toFixed(2);
				item.className = "keyword";
				var style = "font-size:" + Math.round(12 + scale * (slicedata[i].weight - min)/ (max-min) ) + "px; "+
							"color:" + (slicedata[i].weight > middle ? color[0] : color[1]) + "; "
							 + "margin: 2px 0px 0px 20px; float:left;" 
							 + "height:" + (12 + scale)
							+ "; cursor:pointer";
				
				item.setAttribute( "style", style );
				item.onclick = (function(keyword, id, label) {
					return function() {
						listPages(keyword, id, label);
					};
				})( cleanKeyword, "topic",  cleanKeyword);
				chart.appendChild(item);
			}
		}
	};
	var start = document.getElementById("startTimeInput").value;
	var end = document.getElementById("endTimeInput").value;
	xmlHttp.open('get', url+ "&timeFrom="+start+"&timeTo="+end );
	xmlHttp.send(null);
};

var updateDatasource = function(url) {
	var container = document.getElementById("datasourceChart");
	container.innerHTML = "";
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if( (xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
			var xml = xmlHttp.responseText;
			flash.writeFlash({isReplace:false, url:"../weibo/flex/CustomPieChart.swf", id:"datasource", containerId:"datasourceChart", width:"400", height:"200",flashvars:{data:encodeURIComponent(xml)}});
			
			/*var data = JSON.parse( xmlHttp.responseText );
			if( !data ) 
				return;
			 var w = 200, 
				h = 200, 
				r = 80,
				color = d3.scale.category10();
			 var container = document.getElementById("datasourceChart");
				container.innerHTML = "";
			var vis = d3.select("#datasourceChart")
				.append("svg:svg") 
				.data([data])
				.attr("width", w) 
				.attr("height", h)
				.append("svg:g")  
				.attr("transform", "translate(" + 100 + "," + 100 + ")") ;

			var arc = d3.svg.arc()
				.outerRadius(r);
			var pie = d3.layout.pie()
				.value(function(d) { return Number(d.count); }); 

			var arcs = vis.selectAll("g.slice")
				.data(pie)
				.enter()
				.append("svg:g")  
				.attr("class", "slice");  
			arcs.append("svg:path")
				.attr("fill", function(d, i) { return color(i); })
                .attr("d", arc)
                .on("click", function(d){ showWeiboList(d.data.ids); });

			arcs.append("svg:text")
                .attr("transform", function(d) {  
                d.innerRadius = 0;
                d.outerRadius = r;
                return "translate(" + arc.centroid(d) + ")";  
            })
            .attr("text-anchor", "middle")
            .text(function(d, i) { return data[i].name; }); 
*/
		}
	};
	var start = document.getElementById("startTimeInput").value;
	var end = document.getElementById("endTimeInput").value;
	xmlHttp.open('get', url+ "&timeFrom="+start+"&timeTo="+end );
	xmlHttp.send(null);
};


var updateDatasourceTimeline = function(url) {
	var container = document.getElementById("datasourceTrendChart");
	container.innerHTML = "";
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if( (xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
			var xml = xmlHttp.responseText;
			flash.writeFlash({isReplace:false, url:"../weibo/flex/CustomLineChart.swf", id:"datasourceTrend", containerId:"datasourceTrendChart", width:"400", height:"200",flashvars:{data:encodeURIComponent(xml)}});		
		}
	};
	var start = document.getElementById("startTimeInput").value;
	var end = document.getElementById("endTimeInput").value;
	xmlHttp.open('get', url+ "&timeFrom="+start+"&timeTo="+end );
	xmlHttp.send(null);
};

var showWeiboList = function(ids, str, type) {
	/* var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if( ( xmlHttp.readyState == 4 ) && ( xmlHttp.status == 200) ) {
			var result = JSON.parse( xmlHttp.responseText );
			if( !result )
				return;
			var weiboList = document.getElementById("weiboList");
			// time
			// URL
			// content
			var close = document.createElement('div');
			close.innerHTML = "close";
			close.className = "closeWeiboList";
			
			close.onclick = function() {
				d3.select("#weiboPanel").style("display", "none");
			};
			weiboList.appendChild(close);
			
			var table = document.createElement("table");
			weiboList.appendChild( table );
			for(var i=0; i<result.length; i++) {
				var tr = document.createElement('tr');
				var content = document.createElement('td');
				content.innerHTML = "<a href='"+ result[i].url + "'>" + result[i].content +"</a>";
				var time = document.createElement('td');
				
				tr.appendChild( content);
				tr.appendChild( time );
				table.appendChild( tr );
			}
			
			$("#weiboPanel").css("display", "block");
		}
	};*/
	listPages_(ids, str, type);
};
function mapBrand() {
	var brandName = "";
	var brandID = [{name:"pepsi", index:0},
	               {name:"sevenup", index:3},
	               {name:"quaker", index:1},
	               {name:"lays", index:2},
	               {name:"mirinda", index:4},
	               {name:"gatorade", index:5}];
	
	
	var elems = $('.selected');
	for(var i=0; i<elems.size(); i++) {
		var id = elems.eq(i).attr('id');
		for(var j=0; j<brandID.length; j++ ){
			var brand = brandID[j];
			
			if( brand.name == id ) {
				//console.log( brand.index );
				return  brands[brand.index].name;
			}
		}
	}
	return brandName;
}
function listPages_(ids, condition, type){	
	
	  var timeFrom = $("#startTimeInput")[0].value;
	  var timeTo = $('#endTimeInput')[0].value;
	  $("input#keyWord")[0].value = type + ":" +condition;
	  $("input#timeFrom")[0].value = timeFrom;
	  $("input#timeTo")[0].value =  timeTo;
	 
	  document.getElementById("webpageIds").value = !ids?"":ids;
	  
	  document.getElementById("searchCondition").value = "";
	 
	  if( condition )
		  document.getElementById("searchCondition").value = mapBrand() + " > " + condition;
	  document.getElementById("fm").submit();
 }

function updateBuzzVolume(url) {
	var container = document.getElementById('buzzVolumeChart');
	container.innerHTML = '';
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if( (xmlHttp.readyState == 4) && (xmlHttp.status == 200) ) {
			if( !xmlHttp.responseText )
				return;
			
			var data = JSON.parse( xmlHttp.responseText );
			
			var lines = new Array();
			var legends = new Array();
			var i=0;
			for(var key in data ) {
				if( data.hasOwnProperty(key) ){
					legends.push( key );
					// Array.push( Array ) will produce a 1-dimension array.
					lines[i] =  data[key] ;
					i++;
				}
			}
			var option = {
					axes:{
						xaxis:{
							renderer:$.jqplot.DateAxisRenderer,
							tickOptions: {formatString:'%m-%d'},
							numberTicks: 8,
							min: start,
							max: end
							},
						yaxis: {
							min: 0
						}
					},
					highlighter :{
						show: true
					},
					legend: { 
						show:true, 
						location: 'ne' 
					}
			};
			option.series = new Array();
			for(var k=0; k<legends.length; k++) {
				option.series.push( (function(i){
					return { label: legends[i] };
				})(k) );
			}
			console.log( option );
			
			$.jqplot('buzzVolumeChart',lines , option);
			
			/*
			 $("#buzzVolumnChart").unbind("jqplotDataClick");
			 $("#buzzVolumeChart").bind("jqplotDataClick", function(ev, seriesIndex, pointIndex, data){
				console.log( ev );
				console.log( seriesIndex );
				console.log( pointIndex );
				console.log( data );
			});*/
		}
	};
	var start = document.getElementById("startTimeInput").value;
	var end = document.getElementById("endTimeInput").value;
	xmlHttp.open('get', url+ "&timeFrom="+start+"&timeTo="+end );
	xmlHttp.send(null);
}